package config

import (
	"fmt"

	"Projects/NoteSync/internal/common"

	"github.com/BurntSushi/toml"
	"github.com/fsnotify/fsnotify"
)

type Config struct {
	Server *Server
	Log    *Log
}

type Password struct {
	Encrypt bool   `toml:"encrypt"`
	Value   string `toml:"value"`
}

type Server struct {
	Username   string          `toml:"username"`
	Password   string          `toml:"password"`
	HttpIP     string          `toml:"httpIP"`
	IsSSL      bool            `toml:"isSSL"`
	HttpPort   int             `toml:"httpPort"`
	FileFormat string          `toml:"fileFormat"`
	NotePath   string          `toml:"notePath"`
	StorePth   string          `toml:"storePth"`
	Theme      string          `toml:"theme"`
	SyncMode   common.SyncMode `toml:"syncMode"`
	Trans2Html bool            `toml:"trans2html"`
}

type Log struct {
	FilePath   string `toml:"filePath"`
	Level      string `toml:"level"`
	FileFormat string `toml:"fileFormat"`
	FileCount  int    `toml:"fileCount"`
	FileSize   int    `toml:"fileSize"`
}

var SvrConfig Config

func load(path string) {
	SvrConfig = Config{}
	_, err := toml.DecodeFile(path, &SvrConfig)
	if err != nil {
		fmt.Printf("load config file err: %v\n", err)
		return

	}
	fmt.Printf("load config ok, file: %s\n", path)
}

func Init() {
	load(common.AgentConfPath)

	// 监控文件
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		fmt.Printf("error: %v\n", err)
	}
	defer watcher.Close()

	// done := make(chan bool)
	go func() {
		for {
			select {
			case event, ok := <-watcher.Events:
				if !ok {
					return
				}
				fmt.Printf("event: %v\n", event)
				if event.Op&fsnotify.Write == fsnotify.Write {
					fmt.Printf("modified file: %s\n", event.Name)
					Reload()
				}
			case err, ok := <-watcher.Errors:
				if !ok {
					return
				}
				fmt.Printf("error: %v\n", err)
			}
		}
	}()

	err = watcher.Add(common.AgentConfPath)
	if err != nil {
		fmt.Printf("error: %v\n", err)
	}
	fmt.Printf("start watch\n")
	// <-done
}

func Reload() {
	load(common.AgentConfPath)
}
